<template>
  <div>
    <h1>商品列表</h1>
    <!-- 搜索 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字:">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入关键字"
            clearable
          />
        </el-form-item>
        <el-form-item label="ID">
          <el-input v-model="searchForm.id" placeholder="请输入ID" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="toAdd">新增</el-button>
      <el-button type="danger" @click="toDeleteAll">批量删除</el-button>
    </div>
    <!-- 商品列表 -->
    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="ID" />
        <el-table-column prop="prodName" label="商品名称" />
        <el-table-column prop="prodSpu" label="商品SPU" />
        <el-table-column prop="kindName" label="商品类型" />
        <el-table-column prop="typeName" label="商品分类" />
        <el-table-column prop="brandName" label="商品品牌" />
        <el-table-column prop="unitName" label="商品单位" />
        <el-table-column prop="tagName" label="商品标签" />
        <el-table-column prop="appr" label="供应商" />
        <el-table-column prop="prodImage" label="缩略图">
          <template #default="scope">
            <el-image
              :src="scope.row.prodImage"
              style="width: 50px; width: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="prodStatus" label="商品状态">
          <template #default="scope">
            <span v-if="scope.row.prodStatus == 0">草稿</span>
            <span v-if="scope.row.prodStatus == 1">待审核</span>
            <span v-if="scope.row.prodStatus == 2">已上线</span>
            <span v-if="scope.row.prodStatus == 3">已下线</span>
            <span v-if="scope.row.prodStatus == 4">已缺货</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button
              size="small"
              type="success"
              @click="handleProdInfo(scope.row)"
              >商品明细</el-button
            >
            <el-button size="small" type="warning" @click="toaddAtta(scope.row)"
              >商品附件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 20px">
      <div class="demo-pagination-block" style="width: 800px; margin: 0 auto">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新增 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加商品" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="prodKind"
          >
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in prodTypeList"
                :value="item.dictId"
                :key="item.dictValue"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="商品分类"
            :label-width="formLabelWidth"
            prop="prodType"
          >
            <el-tree-select
              v-model="form.prodType"
              :data="TypeList"
              :render-after-expand="false"
              style="width: 240px"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="prodName"
          >
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="SPU名称"
            :label-width="formLabelWidth"
            prop="prodSpu"
          >
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品品牌"
            :label-width="formLabelWidth"
            prop="brandId"
          >
            <el-select
              v-model="form.brandId"
              placeholder="请选择商品品牌"
              clearable
            >
              <el-option
                v-for="item in brandList"
                :label="item.brandName"
                :value="item.brandId"
                :key="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品单位"
            :label-width="formLabelWidth"
            prop="unitId"
          >
            <el-select
              v-model="form.unitId"
              placeholder="请选择商品单位"
              clearable
            >
              <el-option
                v-for="item in unitList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品标签"
            :label-width="formLabelWidth"
            prop="tagId"
          >
            <el-select
              v-model="form.tagId"
              placeholder="请选择商品标签"
              clearable
            >
              <el-option
                v-for="item in tagList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="供应商"
            :label-width="formLabelWidth"
            prop="appr"
          >
            <el-input
              v-model="form.appr"
              autocomplete="off"
              placeholder="请输入供应商"
            />
          </el-form-item>
          <el-form-item
            label="商品缩略图"
            :label-width="formLabelWidth"
            prop="prodImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/goods/index/uploadFile"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 商品附件 -->
    <div>
      <el-dialog
        v-model="dialogAttaFormVisible"
        title="添加商品附件"
        width="500"
      >
        <el-form :model="attaform" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品轮播图"
            :label-width="formLabelWidth"
            prop="attaImages"
          >
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/goods/index/uploadFile"
              :headers="headers"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item
            label="商品视频"
            :label-width="formLabelWidth"
            prop="attaVideo"
          >
            <el-upload
              v-model:file-list="videoList"
              class="upload-demo"
              action="http://localhost:10010/goods/index/uploadFile"
              :headers="headers"
              :before-upload="beforeAvatarUpload"
              :on-change="handleChange"
            >
              <el-button style="border: 1px solid #ff681f"
                ><span style="color: #ff681f">上传视频</span></el-button
              >
              <template #tip>
                <div class="el-upload__tip">
                  作用于商品详情页顶部轮播图的视频介绍,最大限制20MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="上架时间"
            :label-width="formLabelWidth"
            prop="upFlag"
          >
            <el-radio-group fill="#ff681f" v-model="attaform.upFlag">
              <el-radio :value="0">立即上架</el-radio>
              <el-radio :value="1">定时上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="attaform.upFlag == 1"
          >
            <el-date-picker
              v-model="attaform.upTime"
              type="datetime"
              placeholder="请选择上架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="定时下架" :label-width="formLabelWidth">
            <el-switch
              v-model="attaform.downFlag"
              class="ml-2"
              style="--el-switch-on-color: #13ce66"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="attaform.downFlag == 1"
          >
            <el-date-picker
              v-model="attaform.downTime"
              type="datetime"
              placeholder="请选择下架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogAttaFormVisible = false">放弃</el-button>
            <el-button type="primary" @click="toaddAttachment(ruleFormRef)">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getProdList,
  deleteAll,
  getDictList,
  getBrandAll,
  getTypeAll,
  addProd,
  addAttachment,
} from "@/api/api";
import { useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import type { TableInstance } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

import type { UploadUserFile } from "element-plus";

import type { UploadProps } from "element-plus";
const ruleFormRef = ref<FormInstance>();

const router = useRouter();
const tableData = ref([]);
const total = ref(0);
const dialogFormVisible = ref(false);
const dialogAttaFormVisible = ref(false);
const formLabelWidth = "140px";
//商品类型
const prodTypeList = ref([]);
const TypeList = ref([]);

const brandList = ref([]);
const unitList = ref([]);
const tagList = ref([]);

const multipleTableRef = ref<TableInstance>();
const fileList = ref<UploadUserFile[]>([]);
const multipleSelection = ref<any[]>([]);
const searchForm = ref({
  id: null,
  keyWord: null,
  pageNum: 1,
  pageSize: 2,
});
//商品表单
const form = ref({
  appr: null,
  brandId: null,
  brandName: null,
  createBy: null,
  createTime: null,
  kindName: null,
  prodId: null,
  prodImage: null,
  prodKind: null,
  prodName: null,
  prodSpu: null,
  prodStatus: null,
  prodType: null,
  tagId: null,
  tagName: null,
  typeName: null,
  unitId: null,
  unitName: null,
  updateBy: null,
  updateTime: null,
});
const restForm = () => {
  form.value = {
    appr: null,
    brandId: null,
    brandName: null,
    createBy: null,
    createTime: null,
    kindName: null,
    prodId: null,
    prodImage: null,
    prodKind: null,
    prodName: null,
    prodSpu: null,
    prodStatus: null,
    prodType: null,
    tagId: null,
    tagName: null,
    typeName: null,
    unitId: null,
    unitName: null,
    updateBy: null,
    updateTime: null,
  };
  imageUrl.value = "";
};
//商品附件表单
const attaform = ref({
  attaId: null,
  attaImages: null,
  attaVideo: null,
  createBy: null,
  createTime: null,
  downFlag: null,
  downTime: null,
  prodId: null,
  upFlag: null,
  upTime: null,
  updateBy: null,
  updateTime: null,
});
//商品明细
const handleProdInfo = (row: any) => {
  router.push("/home/prodInfo/" + row.prodId);
};

//添加附件表单
const toaddAttachment = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const images = [];
      if (videoList.value.length > 0) {
        attaform.value.attaVideo = videoList.value[0].response.data;
      }

      fileList.value.forEach((item) => {
        images.push(item.response.data);
      });
      attaform.value.attaImages = JSON.stringify(images);
      addAttachment(attaform.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogAttaFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//视频
const videoList = ref<UploadUserFile[]>([]);

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "video/mp4") {
    console.log(rawFile.type);
    ElMessage.error("只能上传视频格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error("视频大小不能大于20MB!");
    return false;
  }
  return true;
};

const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  fileList.value = fileList.value.slice(-3);
};

//商品轮播图
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

//图片删除函数
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
//图片预览
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//打开商品附件弹框
const toaddAtta = (row: any) => {
  attaform.value.prodId = row.prodId;
  dialogAttaFormVisible.value = true;
};

//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      form.value.prodImage = imageUrl.value;
      addProd(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadList();
          restForm();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};
//添加商品校验
const rules = ref<FormRules<any>>({
  prodName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  prodType: [
    { required: true, message: "商品分类不能为空", trigger: "change" },
  ],
  brandId: [{ required: true, message: "商品品牌不能为空", trigger: "change" }],
  unitId: [{ required: true, message: "商品单位不能为空", trigger: "change" }],
  tagId: [{ required: true, message: "商品标签不能为空", trigger: "change" }],
  prodKind: [{ required: true, message: "商品类型不能为空", trigger: "blur" }],
  prodImage: [
    {
      validator(rule: any, value: any, callback: any) {
        if (imageUrl.value === "" || imageUrl.value == null) {
          callback(new Error("图片不能为空"));
        } else {
          callback();
        }
      },
      required: true,
      message: "商品图片不能为空",
      trigger: "blur",
    },
  ],
  prodSpu: [{ required: true, message: "Spu名称不能为空", trigger: "blur" }],
  appr: [{ required: true, message: "供应商名称不能为空", trigger: "blur" }],
  upFlag: [{ required: true, message: "上架时间不能为空", trigger: "change" }],
  attaImages: [
    {
      validator(rule: any, value: any, callback: any) {
        if (fileList.value.length == 0 || fileList.value == null) {
          callback(new Error("商品轮播图不能为空"));
        } else {
          callback();
        }
      },
      required: true,
      message: "商品轮播图不能为空",
      trigger: "blur",
    },
  ],
  attaVideo: [
    {
      validator(rule: any, value: any, callback: any) {
        if (videoList.value.length == 0 || videoList.value == null) {
          callback(new Error("商品视频不能为空"));
        } else {
          callback();
        }
      },
      required: true,
      message: "商品视频不能为空",
      trigger: "blur",
    },
  ],
});

const headers = ref({
  token: sessionStorage.getItem("token"),
});
const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};

//新增弹框
const toAdd = () => {
  dialogFormVisible.value = true;
};

//批量删除
const toDeleteAll = () => {
  ElMessageBox.confirm("数据删除后无法恢复,您确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAll(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};
//多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//分页回调
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};
const loadList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
onMounted(() => {
  loadList();
  //获取商品类型
  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      prodTypeList.value = res.data.data;
    }
  });
  //获取品牌
  getBrandAll().then((res) => {
    if (res.data.code == 200) {
      brandList.value = res.data.data;
    }
  });
  //获取商品单位
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  //获取商品标签
  getDictList(3).then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });
  //商品分类
  getTypeAll().then((res) => {
    if (res.data.code == 200) {
      TypeList.value = res.data.data;
    }
  });
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
